<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Env;
use think\View;

/**
 * 搜索管理
 *
 * @icon fa fa-circle-o
 */
class Search extends Api
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $model = null;
    private $view;


    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Product;
        $this->view = new View();

    }

    public function s()
    {
        $lang = $this->request->request("lang",'zh');
        $kwords = $this->request->request("kwords");
        $suri = $this->request->server('REQUEST_URI');
        $ktype = $this->request->request("ktype",0);//0-产品 1-新闻
        //当前页
        $page = $this->request->request("pageNumber",1);
        //分页大小
        $pagesize = $this->request->request("pageSize",10);
        $where = ['status'=>'normal'];
        $modulePage = 'search-news';
        if(strpos($suri,'pageNumber')){
            $suri = mb_substr($suri,0,(strpos($suri,'pageNumber')-5));
//            var_dump($suri);die;
        }
        $data = ['suri'=>$suri];//分页使用
        if($ktype == 1){
            $this->model = new \app\common\model\News;
            $list = $this->model->where($where)->where('LOWER(title) LIKE "%'.strtolower($kwords).'%"')->paginate($pagesize, false, ['page' => $page]);
        }else{
            $modulePage = 'search-center';
            $list = $this->model
                ->field(['id','content','content_zh'])
                ->where($where)
                ->where('LOWER(content->\'$.product_name\') LIKE "%'.strtolower($kwords).'%"')
//                ->where("content_zh->'$.product_name'",'like','%'.$kwords.'%')
                ->paginate($pagesize, false, ['page' => $page]);
            $producsZh = [];
            foreach ($list as $produc){
                $obj =  json_decode($produc['content_zh'],1);
                $obj['id'] = $produc['id'];
                $content = json_decode($produc['content'],1);
//                                var_dump($content['product_name']);die;
                if(isset($content['product_name'])){
                    $pagePath = str_replace(' ','-',$content['product_name']);//静态文件地址用产品名称
                    $obj['product_name'] = $content['product_name'];
                }else{
                    $pagePath = 'product-'.$produc['id'].'.html';
                }
                $obj['pagePath'] = $pagePath;
                $producsZh[] = $obj;
            }
            $data['products'] = $producsZh;
        }
        $data['fromLan'] = 'zh';//原语言
        $data['toLan'] = $lang;//目标语言
        $data['pagelist'] = $list;//$pagelist分页使用
        $data['modulePage'] = $modulePage;
//        $data['domain'] = Env::get('app.domain');

        $data['domain'] = $data['domainLan'] = 'https://'.($data['toLan'] === 'zh'?'cn':$data['toLan']).'.chqwire.net';
        return $this->view->fetch('cn/'.$modulePage, $data);
    }

}
